#include "Pickup.h"
namespace SLG
{
	Pickup::Pickup(World* wd,Camera* c,int w, int h, bool m)
		: m_world(wd),
		m_Camera(c),
		m_screenWidth(w),
		m_screenHeight(h),
		m_fManager(wd->m_Figure->m_fManager),
		m_mode(m)
	{
		m_hscreenWidth=w/2;
		m_hscreenHeight=h/2;
		m_fp=fopen("Pickup.log","ab");
	}

	Pickup::~Pickup(void)
	{
		fclose(m_fp);
	}

	void Pickup::Log(int32 d)
	{
		fprintf(m_fp,"Fid:%d clicked!\n",d);
	}

	uint32 Pickup::CheckPickingInCell(D3DXVECTOR2* pos)
	{
		return m_world->GetCurCellFid();
	}

	uint32 Pickup::CheckPickingInWorld(D3DXVECTOR2* pos)
	{
		Ray* mouseRay=m_coord->ScreenToWorldCoord(pos);
		float minObj=1000.0f;
		int fid=-1;;
		for(vector<FIGURE>::iterator iter=m_fManager->m_data.begin();iter<m_fManager->m_data.end();iter++)
		{
			float dist;
			if(mouseRay->Intersects(*iter->aabb,&dist))
			{
				if(dist<minObj)
				{
					fid=iter->id;
					minObj=dist;
				}
			}
		}
		Log(fid);
		delete mouseRay;
		return fid;
	}

	void Pickup::PickCell(World* w,D3DXVECTOR2* pos)
	{
		Ray* mouseRay=m_coord->ScreenToWorldCoord(pos);
		D3DXVECTOR3 inter_point ;
		if(mouseRay->Intersects(Plane(D3DXVECTOR3(0,1,0),0),&inter_point))
		{
			w->UpdateCursorCell(&inter_point);
		}
	}

	void Pickup::Picking(Menu* m,D3DXVECTOR2* pos)
	{
		int32 id=-1;
		if(id=m->GetMenuID(pos))
		{
		}
		else
		{
			PickObj(m,pos);
		}
	}

	void Pickup::PickObj(Menu* m,D3DXVECTOR2* pos)
	{
		int32 id=CheckPickingInCell(pos);
		if(id!=-1)
		{
			D3DXVECTOR3 wpos=m_world->GetCellPos();
			//D3DXVECTOR2 spos=m_coord.WorldToScreenCoord(&wpos);
			m->AddBattle(wpos);
		}
	}
}